<!-- 施工巡查 -->
<template>
<div class="buildMain">
    <map-container ref="mapContainer"></map-container>
    <!-- 搜索框 -->
    <div style="width: calc(100% - 90px); margin: 10px 20px; height: 32px; background: #fff; z-index: 99; position: absolute; left: 10px; border-radius: 5px; border: 1px solid #f3f3f3;">
        <!-- 下拉框部分 -->
        <div style="float: left; height: 20px; line-height: 20px; width: 75px; margin: 5px 0px; border-right: 1px solid #f3f3f3;" @click="showPicker = true">
            <div style="height: 100%; ">
                <div style="float: left; line-height: 100%; width: 16px;">
                    <img src="https://nfzjszlb.jst.zj.gov.cn/security/xiala.png" />
                </div>
                <div style="width: calc(100% - 32px); float: left; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{form.cityname}}</div>
            </div>
        </div>
        <!-- 文本框部分 -->
        <div style="float: left;  height: 32px; line-height: 32px; width: calc(100% - 120px);">
            <van-search v-model="inputSousuo" placeholder="请输入户主姓名" :action="false" @search="_searchData('')" @clear="_searchClear" />
        </div>
    </div>
    <!-- 列表 -->
    <div style="width: 32px; height: 32px; background: #fff; z-index: 99; position: absolute; right: 20px; top: 10px; border-radius: 5px; border: 1px solid #f3f3f3;" @click="_tiaoZhuan">
        <div style="text-align: center;">
            <img style="height: 12px;" src="https://nfzjszlb.jst.zj.gov.cn/security/liebiao.png" />
        </div>
        <div style="text-align: center; font-size: 10px; line-height: 16px;">列表</div>
    </div>
    <!-- 图例 -->
    <legend-tool ref="legendTool" :legendDatas="legendDatas"></legend-tool>
    <!-- 区域下拉框-弹框 -->
    <van-popup v-model="showPicker" position="bottom">
        <van-cascader v-model="form.citycode" title="选择所属区域" :options="options" @change="_onChange" @finish="_onFinish" :closeable="false" style="position: relative;" />
        <span style="position: absolute; top: 0%; right: 10px;font-size: 16px;height: 48px;line-height: 48px;" @click="_closeTK">确定</span>
    </van-popup>
    <!-- 搜索结果-底部弹框 -->
    <div v-show="showTK" class="sousuo-content" style="width:100vw;height:40vh;background:#ffffff;z-index:99;position: fixed;bottom: 0;overflow-y: auto;">
        <div style="height: 4vh; background: #1989fa;" @click="showTK=false,ListDataOption=[]">
            <img src="https://nfzjszlb.jst.zj.gov.cn/security/close.png" style="margin:1vh 2vw;float: right;" />
        </div>
        <van-list v-model="loading" :offset="4" :finished="finished" finished-text="没有更多了" class="toBeCheckedList-middle1">
            <van-cell v-for="(item, index) in ListDataOption" :key="index" @click="_oneListClick(item)">
                <ul class="toBeCheckedList-middle">
                    <li class="toBeCheckedList-middle2">
                        户主姓名：{{ item.XM }}
                        <span style="float: right" v-if="item.SFXC == 1">已巡查</span>
                        <span style="float: right" v-else>未巡查</span>
                    </li>
                    <li class="toBeCheckedList-middle4">系统施工进度：{{ item.WF_NAME }}</li>
                    <li class="toBeCheckedList-middle3">地址：{{ item.ADDRESS }}</li>

                </ul>
            </van-cell>
        </van-list>
    </div>

</div>
</template>

<script>
import dd from 'gdt-jsapi'
import Pubsub from 'pubsub-js'
import * as api from '../../utils/api_gis'
import {
    GetAdministrative,
    getDatalistForTree,
} from '../../utils/api'
import {
    GSA_Search2
} from '@/common/commonApi'
import * as esriLoader from "esri-loader";
import MapManager from "../../core/mapManager"
import MapContainer from './MapContainer'
import legendTool from "./public/legendTool.vue"
export default {
    data() {
        return {
            rowguid: "",
            isIquery: false,
            ifEcho: false,
            legendDatas: [{
                    title: "定位放样",
                    color: "#FFA500"
                },
                {
                    title: "基槽验线",
                    color: "#40E0D0"
                },
                {
                    title: "一层建模",
                    color: "#9ACD32"
                },
                {
                    title: "竣工验收",
                    color: "#6A5ACD"
                },
            ],
            showPicker: false,
            citycode: "",
            cityname: "",
            options: [],
            form: {
                cityname: "选择区域",
                citycode: "",
            },
            //底部详情框
            showTK: false,
            inputSousuo: "",
            // startPage: 0,
            loading: false,
            finished: false,
            ListDataOption: [],
            //当前定位
            geometryHX: null,

        };
    },

    components: {
        MapContainer,
        legendTool,
    },

    computed: {},
    //注意：修改组件请添加对应的修改版本、日期、功能、注释！！！！
    //方法：方法命名请以下划线_开头！！！！
    //其它项复制粘贴过来的代码，请将无用的参数删除，一个js类用到一个方法不要粘整个js过来！！！！
    methods: {
        //初始化判断是store是否存在，判断是第一次打开，还是返回回显
        _echo() {
            let search = this.$store.state.buildMainSearch //返回页面取出来
            if (typeof (search) != "undefined") {
                if (typeof (search.citycode) != "undefined" && typeof (search.cityname) != "undefined" && typeof (search.inputSousuo) != "undefined") {
                    this.form.citycode = search.citycode
                    this.form.cityname = search.cityname
                    this.inputSousuo = search.inputSousuo
                    this.geometryHX = search.geometryHX
                    this.rowguid = search.rowguid
                    if (search.isIquery == true) {
                        Pubsub.publish("openQuqry");
                        this._searchData(search.rowguid)
                    } else {
                        this._searchData("")
                    }
                    this._getXianOpenDataView(search.citycode)
                    this._locationHX(this.geometryHX)
                    this.ifEcho = false
                }
            }
        },
        //获取url地址中的某一个参数值
        _getUrlParam(paraName) {
            var url = decodeURI(document.location.toString());
            var arrObj = url.split("?");

            if (arrObj.length > 1) {
                var arrPara = arrObj[1].split("&");
                var arr;
                for (var i = 0; i < arrPara.length; i++) {
                    arr = arrPara[i].split("=");
                    if (arr != null && arr[0] == paraName) {
                        return arr[1];
                    }
                }
                return "";
            } else {
                return "";
            }
        },
        //列表跳转
        _tiaoZhuan() {
            this.ifEcho = false;
            this.$router.push({
                path: '/ConstructionInspection'
            })
        },
        //···············头部区域选择相关···············
        //所属区域检查
        _getXianOpenDataView: async function (data) {
            if (window.localStorage.getItem('citycode') != "330000000000") {
                this.options = [{
                    text: window.localStorage.getItem('cityName'),
                    value: window.localStorage.getItem('citycode'),
                    isHasChild: true
                }]
            }
            const res = await getDatalistForTree(data)
            res.data.data.forEach((item) => {
                let obj = {
                    text: item.cityname,
                    value: item.citycode,
                }
                if (item.citycode.toString().substring(9, 12) !== "000") {

                } else {
                    obj['children'] = []
                }
                this.options.push(obj)
            })
        },
        _onChange({
            value,
            selectedOptions,
            tabIndex
        }) {
            if (value.toString().substring(9, 12) !== "000" || selectedOptions[0].isHasChild) {} else {
                this._getXZQH(value, selectedOptions, tabIndex)
            }
            this._onFinish({
                value,
                selectedOptions,
                tabIndex
            })
        },
        _onFinish({
            value,
            selectedOptions,
            tabIndex
        }) {
            this.form.cityname = selectedOptions[selectedOptions.length - 1].text;
            this.form.citycode = value
            this._locationQH(value)
        },
        _getXZQH: async function (value, selectedOptions, tabIndex) {
            const res = await GetAdministrative(value)
            selectedOptions[tabIndex].children = []
            if (res.data.data.length > 0) {
                res.data.data.forEach((element) => {
                    let obj = {
                        text: element.cityname,
                        value: element.citycode
                    }
                    if (element.citycode.toString().substring(9, 12) !== "000") {} else {
                        obj['children'] = []
                    }
                    selectedOptions[tabIndex].children.push(obj)
                })
            }
        },
        _closeTK() {
            this.showPicker = false;
            this.showTK = false;
            // this.startPage = 0;
            this.ListDataOption = [];
            this.rowguid = "";
            this.isIquery = false;
        },
        //······························
        //根据头部选择中的区划进行定位
        _locationQH(code) {
            const self = this
            code += ""
            if (code.substring(0, 12) == "330000000000") { //省级
                if (window.g.MapConfiguration.InitExtent) {
                    let initExtent = new self.Extent(window.g.MapConfiguration.InitExtent);
                    self.geometryHX = initExtent //.center;
                    self.mapView.goTo({
                        target: initExtent.center,
                        // zoom: 13
                    }, {
                        easing: "ease-out",
                        duration: 1000
                    });
                }
            } else if (code.substring(4, 12) == "00000000") { //市级
                let city = self.cityDivisions.find(item => {
                    return item.attributes.code == code.substring(0, 6)
                })
                self.geometryHX = city.geometry.extent //.center
                self.mapView.goTo({
                    target: city.geometry.extent.center,
                    // zoom: 13
                }, {
                    easing: "ease-out",
                    duration: 1000
                });
            } else if (code.substring(6, 12) == "000000") { //区县
                let quxian = self.blockDivisions.find(item => {
                    return item.attributes.code == code.substring(0, 6)
                })
                if (typeof (quxian) == "undefined") {
                    quxian = self.blockDivisions.find(item => {
                        return item.attributes.code == code
                    })
                }
                self.geometryHX = quxian.geometry.extent //.center
                self.mapView.goTo({
                    target: quxian.geometry.extent.center,
                    // zoom: 16
                }, {
                    easing: "ease-out",
                    duration: 1000
                });
            } else { //村镇
            }
        },
        //回显定位
        _locationHX(geometryHX) {
            const self = this
            this.$nextTick(() => {
                setTimeout(() => {
                    self.mapView.goTo({
                        target: geometryHX.center,
                        // zoom: 16
                    }, {
                        easing: "ease-out",
                        duration: 1000
                    });
                }, 2000)
            })
        },
        //获取当前citycode加载对应的图层（全省加载所有图层）---有对应的掩膜定位
        _addLayers() {
            const self = this
            let player = new self.MapImageLayer({
                title: window.g.BuildMain.layer.title,
                id: window.g.BuildMain.layer.title + "_BuildMain",
                url: window.g.BuildMain.layer.url,
            });
            self.mapView.map.add(player)
        },
        //搜索
        _searchData(guid) {
            // this.startPage = 0
            this.ListDataOption = []
            this._onLoad(guid)
        },
        _onLoad(guid) {
            // this.startPage += 1
            this._getData(guid)
        },
        async _getData(guid) {
            const self = this
            let citycode = self.form.citycode + ""
            let params = []

            //guid不为空说明是i查询的搜索
            if (guid != "" && guid != undefined) {
                params.push({
                    "field": "ROW_GUID",
                    "value": guid,
                    "operator": "like",
                    "link": "AND"
                }) //房屋编号
            } else {
                params.push({
                    "field": "HOUSEAPPLICANT",
                    "value": self.inputSousuo,
                    "operator": "like",
                    "link": "AND"
                }) //户主姓名
                params.push({
                    "field": "CUN",
                    "value": citycode.replace(/(0+)$/g, ''),
                    "operator": "like"
                }) //区县
            }
            self.showTK = true
            const webResult = await GSA_Search2('d9829ac6-e75e-4bb4-82e9-3b98403036ae', params, citycode)
            this.loading = false
            let pageList = webResult.Data
            if (pageList.length > 0) {
                this.finished = false
                this.ListDataOption.push(...pageList)
            } else {
                this.finished = true
            }
            if (this.ListDataOption.length >= webResult.Data.length) {
                this.finished = true
            }
        },
        //搜索清空
        _searchClear() {
            this.showTK = false
            this.ListDataOption = []
        },
        //底部弹框单行单击跳转
        _oneListClick(item) {
            //跳转
            this.ifEcho = true;
            this.$router.push({
                path: '/ConstructionInspectionPage',
                query: {
                    data: JSON.stringify(item),
                    index: item.SFXC,
                    type: 'map',
                    cityCode: this.form.citycode
                }
            })
        },

    },

    beforeRouteLeave(to, from, next) {
        if (this.ifEcho) {
            //离开路由时把位置存起来
            this.$store.state.buildMainSearch = {
                citycode: this.form.citycode + "",
                cityname: this.form.cityname,
                inputSousuo: this.inputSousuo,
                isIquery: this.isIquery,
                geometryHX: this.geometryHX,
                rowguid: this.rowguid
            }
        } else {
            this.$store.state.buildMainSearch = {}
        }
        next()
    },

    mounted() {
        const self = this

        dd.ready(function () {
            dd.setTitle({
                    title: '施工巡查',
                })
                .then((res) => {})
                .catch((err) => {
                    console.error(err)
                })
        })
        MapManager.getMapViewByIDAsy("mainMap").then((mapView) => {
            self.mapView = mapView;
            esriLoader
                .loadModules([
                    "esri/layers/MapImageLayer",
                    "esri/layers/FeatureLayer",
                    "esri/layers/GraphicsLayer",
                    "esri/Graphic",
                    "esri/geometry/Extent",
                    "esri/geometry/Point",
                    "esri/geometry/Polyline",
                    "esri/geometry/Polygon",
                    "esri/core/watchUtils",
                ])
                .then(
                    ([
                        MapImageLayer,
                        FeatureLayer,
                        GraphicsLayer,
                        Graphic,
                        Extent,
                        Point,
                        Polyline,
                        Polygon,
                        watchUtils,
                    ]) => {
                        self.MapImageLayer = MapImageLayer;
                        self.FeatureLayer = FeatureLayer;
                        self.GraphicsLayer = GraphicsLayer;
                        self.Graphic = Graphic;
                        self.Extent = Extent
                        self.Point = Point;
                        self.Polyline = Polyline;
                        self.Polygon = Polygon;
                        self.watchUtils = watchUtils;
                        //添加市级、区县要素
                        self.cityDivisions = MapManager.getAdministrativeDivisions()
                        self.blockDivisions = MapManager.getAdministrativeDivisions(1)
                        self._addLayers()

                        let search = self.$store.state.buildMainSearch
                        if (typeof (search) != "undefined" && JSON.stringify(search)!='{}') {
                            self.$nextTick(() => {
                                self._echo()
                            })
                        } else {
                            //1、获取当前用户级别
                            self.citycode = window.localStorage.getItem('citycode')
                            self.cityname = window.localStorage.getItem('cityName')
                            if (self.citycode == null) {
                                self.citycode = self._getUrlParam("citycode")
                            }
                            if (self.cityname == null) {
                                self.cityname = self._getUrlParam("cityname")
                            }
                            if (self.citycode != "330000000000"){
                                self.form.citycode = self.citycode
                                self.form.cityname = self.cityname
                            }
                            self.$nextTick(() => {
                                setTimeout(() => {
                                    self._locationQH(self.form.citycode)
                                }, 1000)
                            })
                            self._getXianOpenDataView(self.citycode)
                        }
                    }
                );
        });
        self.mapPopupFeatureHander = Pubsub.subscribe("mapPopupFeature", (msg, data) => {
            if (data) {
                self.isIquery = true;
                self.geometryHX = data.geometry.extent
                self.rowguid = data.attributes['row_guid']
                self._searchData(data.attributes['row_guid'])
            }
        })
        self.colseBottomTKHander = Pubsub.subscribe("closeBottomTK", (msg, data) => {
            self.showTK = false
            self.ListDataOption = []
        })
        self.clearIQuqryHander = Pubsub.subscribe("clearIQuqry", (msg, data) => {
            self.rowguid = ""
            self.geometryHX = null
        })

    },

    beforeDestroy() {
        this.mapView.graphics.removeAll()
    },

}
</script>

<style lang="scss">
.buildMain .van-search {
    padding: 0 0;
    height: 30px;
}

.buildMain .van-search__content {
    background: #ffffff;
    height: 30px;
}

.buildMain .van-search .van-cell {
    padding: 2px 0;
}

.buildMain .van-cell {
    line-height: 30px;
}

.buildMain .van-field__left-icon {
    line-height: 30px;
}

.buildMain .van-cell__value {
    line-height: 30px;
}
</style>
